<template>
  <div class="flexP">
    <el-steps :active="active" align-center>
      <el-step title="商品基本信息"></el-step>
      <el-step title="详细信息"></el-step>
      <el-step title="其他信息"></el-step>
    </el-steps>
    <div class="flexcenter">
      <el-form ref="form" :model="form" label-width="80px" size="small" v-if="active==0">
        <el-form-item label="商品名称">
          <el-input v-model="form.title" style="width:300px"></el-input>
        </el-form-item>
        <el-form-item label="平台分类">
          <el-cascader
            v-model="categoryid"
            :options="categoryList"
            style="width:300px"
            @change="handleChange"
          ></el-cascader>（设置平台分类可同时发布到指点商城）
        </el-form-item>
        <el-form-item label="商品分类">
          <el-cascader
            v-model="co_categoryid"
            :options="co_categoryList"
            style="width:300px"
            @change="handleChanges"
          ></el-cascader>（卖家设置的分类）
        </el-form-item>

        <el-form-item label="商品属性">
          <div class="el-input__inner" style="height:auto">
            <span class="parmarBtn" v-for="(item,index) in form.param" :key="index">
              {{item.title}}：{{item.description}}
              <i
                @click="form.param.splice(index,1)"
                class="el-icon-error"
              ></i>
            </span>
            <el-button size="mini" @click="openAttribute('')">新增属性</el-button>
          </div>
        </el-form-item>
        <el-form-item label="商品规格">
          <div class="el-specItem" style="height:auto">
            <div v-for="(item,index) in form.spec" :key="index" class="specItem">
              <div>
                <i @click="form.spec.splice(index,1)" class="el-icon-error"></i>
                商品属性{{index+1}}
              </div>
              <div>
                <div class="specVal">
                  <span class="valTit">名称</span>
                  <el-input v-model="item.title" size="mini" style="width:100px"></el-input>
                </div>
                <div class="specVal">
                  <span class="valTit">规格值</span>
                  <div class="inputBox" v-for="(items,indexs) in item.list" :key="indexs">
                    <el-input v-model="items.name" @blur="updateTable" style="width:100px"></el-input>
                    <i @click="form.spec[index].list.splice(indexs,1)" class="el-icon-error"></i>
                  </div>
                  <div>
                    <el-button size="mini" @click="form.spec[index].list.push({name:''})">新增</el-button>
                  </div>
                </div>
              </div>
            </div>
            <el-button class="addBtn" size="mini" @click="addSpecs">新增规格</el-button>
            <!-- <el-button size="mini" @click="updateTable()">更新规格表</el-button> -->
            <el-table ref="multipleTable" :data="form.option" size="mini" border>
              <el-table-column prop="name" label="规格"></el-table-column>
              <el-table-column label="图片">
                <template slot-scope="scope">
                  <el-upload
                    class="avatar-uploader"
                    :action="action"
                    :data="uploadData"
                    :show-file-list="false"
                    :on-success="(res, file) => specsSuccess(res, file,scope.$index)"
                    :before-upload="beforeUpload"
                    :disabled="scope.row.disabled"
                  >
                    <img v-if="scope.row.thumb" :src="scope.row.thumb" class="avatar" />
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </template>
              </el-table-column>
              <el-table-column label="商品编码">
                <template slot-scope="scope">
                  <el-input :disabled="scope.row.disabled" v-model="scope.row.goods_no"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="规格名称">
                <template slot-scope="scope">
                  <el-input :disabled="scope.row.disabled" v-model="scope.row.title"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="零售价">
                <template slot-scope="scope">
                  <el-input :disabled="scope.row.disabled" v-model="scope.row.old_price"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="一口价">
                <template slot-scope="scope">
                  <el-input :disabled="scope.row.disabled" v-model="scope.row.price"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="成本价">
                <template slot-scope="scope">
                  <el-input :disabled="scope.row.disabled" v-model="scope.row.cost_price"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="库存">
                <template slot-scope="scope">
                  <el-input :disabled="scope.row.disabled" v-model="scope.row.stock"></el-input>
                </template>
              </el-table-column>
              <el-table-column align="ceneter" label="操作">
                <template slot-scope="scope">
                  <el-button
                    v-if="scope.row.disabled"
                    type="text"
                    size="mini"
                    @click="scope.row.disabled=false"
                  >启用</el-button>
                  <el-button v-else type="text" size="mini" @click="scope.row.disabled=true">禁用</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
        <el-form-item label="总库存">
          <el-input disabled v-model="form.stock" style="width:100px;margin-right:10px"></el-input>
        </el-form-item>
        <el-form-item label="商品运费">
          <el-input v-model="form.postage" style="width:100px;margin-right:10px"></el-input>
          <el-checkbox v-model="checked">包邮</el-checkbox>
        </el-form-item>
      </el-form>
      <el-form :model="form" label-width="80px" v-if="active==1">
        <el-form-item label="商品主图">
          <el-upload
            class="avatar-uploader"
            :action="action"
            :data="uploadData"
            :show-file-list="false"
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
          >
            <img v-if="form.thumb" :src="form.thumb" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="轮播图">
          <div style="display:inline-block" v-if="form.thumbUrl">
            <span class="avatars" v-for="(item,index) in form.thumbUrl.split(',')" :key="index">
              <img :src="item" class="avatar" />
              <span class="deleteIcon" @click="handleRemove(index)">
                <i class="el-icon-delete"></i>
              </span>
            </span>
          </div>
          <span style="display: inline-block;">
            <el-upload
              class="avatar-uploader"
              :action="action"
              :data="uploadData"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeUpload"
            >
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </span>
        </el-form-item>
        <el-form-item label="商品详情">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" v-model="form.content"></el-input>
        </el-form-item>
        <el-form-item label="详情图片">
          <div style="display:inline-block" v-if="form.contentImg">
            <span class="avatars" v-for="(item,index) in form.contentImg.split(',')" :key="index">
              <img :src="item" class="avatar" />
              <span class="deleteIcon" @click="handleRemoveC(index)">
                <i class="el-icon-delete"></i>
              </span>
            </span>
          </div>
          <span style="display: inline-block;">
            <el-upload
              class="avatar-uploader"
              :action="action"
              :data="uploadData"
              :show-file-list="false"
              :on-success="handleAvatarSucce"
              :before-upload="beforeUpload"
            >
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </span>
        </el-form-item>
      </el-form>
      <el-form :model="form" label-width="120px" v-if="active==2">
        <el-form-item label="库存计算方式">
          <el-radio-group v-model="form.typeStock">
            <el-radio :label="1">下单减库存</el-radio>
            <el-radio :label="2">支付减库存</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上架时间">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">立即上架</el-radio>
            <el-radio :label="2">暂时不上传</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="上传云编辑">
          <el-radio-group v-model="form.is_save">
            <el-radio :label="1">立即上架</el-radio>
            <el-radio :label="2">暂时不上传</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="使用价格">
          <el-input v-model="form.use_price" style="width:300px"></el-input>
        </el-form-item>
        <div>
          <el-alert
            :closable="false"
            title=" 云编辑说明：将编辑好的商品信息上传到云端，供其他商家使用，您可以自定义使用价格，当其他商家想获得你的商品详情使用权时，则需要向你支付你自定义的费用。您选择上传到云端后，我们将对你发布的产品信息进行审核，确保和云端中的产品详情重复率不超过20%，否则上传失败。"
            type="info"
          ></el-alert>
        </div>-->
      </el-form>
    </div>
    <el-card style="text-align:center">
      <el-button v-if="active>0" @click="back">返回</el-button>
      <el-button v-if="active<2" @click="next">下一步</el-button>
      <el-button v-if="active==2" @click="finsh">完成</el-button>
    </el-card>
    <ProductAttribute ref="attributeEdit" @saveAttribute="saveAttribute" />
  </div>
</template>
<script>
import vEditor from "@/components/vEditor/vEditor";
import ProductAttribute from "./ProductAttribute";
import httpRequest from "@/utils/httpRequest";
import { mapState, mapActions } from "vuex";

import {
  get_category_list_all,
  get_goods_info,
  add_goods_info,
  edit_goods_info
} from "@/utils/api/market";
export default {
  components: {
    vEditor,
    ProductAttribute
  },

  computed: {
    ...mapState({
      company: state => state.company
    }),
    specChang() {
      return JSON.stringify(this.form.spec);
    },
    stockTotal() {
      let totalPrice = 0;
      if (this.form.option) {
        totalPrice = this.form.option.reduce(
          (total, item) => total + (item.stock - 0),
          0
        );
      }

      return totalPrice;
    }
  },
  watch: {
    specChang(newVal, oldVal) {
      console.log(newVal, oldVal);

      // this.updateTable();
    },
    stockTotal(newVal, oldVal) {
      this.form.stock = this.stockTotal;
    }
  },
  data() {
    return {
      categoryList: [], //商品类型
      co_categoryList: [], //商家商品类型
      imageUrl: "",
      active: 0,
      checked: false,
      action: httpRequest.adornUrl("/market/upload/upload"),
      uploadData: { type: "2" },
      categoryid: "",
      co_categoryid: "",
      form: {
        goods_id: "",
        categoryid: "",
        co_categoryid: "",
        title: "",
        thumb: "",
        thumbUrl: "",
        postage: "",
        content: "",
        contentImg: "",
        stock: "",
        typeStock: 1,
        status: 1,
        is_save: 1,
        use_price: "",
        param: [],
        spec: [],
        option: []
      }
    };
  },
  created() {
    /**  获取产品类型 **/

    get_category_list_all({ to_co_id: this.company.id }).then(res => {
      if (res.code == 200) {
        let data = res.data;
        let bbb = JSON.parse(
          JSON.stringify(data)
            .replace(/two/g, "children")
            .replace(/name/g, "label")
            .replace(/id/g, "value")
        );
        this.co_categoryList = bbb;
      }
    });

    get_category_list_all({ to_co_id: "pingtai" }).then(res => {
      console.log(res);
      if (res.code == 200) {
        let data = res.data;
        let bbb = JSON.parse(
          JSON.stringify(data)
            .replace(/two/g, "children")
            .replace(/three/g, "children")
            .replace(/name/g, "label")
            .replace(/id/g, "value")
        );
        this.categoryList = bbb;
      }
    });
  },
  methods: {
    /**初始化数据 */

    initProduct(id) {
      if (id) {
        get_goods_info({ id: id }).then(res => {
          if (res.code == 200) {
            this.form = Object.assign({}, this.form, res.data);

            this.form.goods_id = id;
            this.form.option.forEach(element => {
              this.$set(element, "disabled", false);
            });
            this.categoryid = this.form.categoryid;
            this.co_categoryid = this.form.co_categoryid;
          }
        });
      } else {
        this.form = {
          goods_id: "",
          categoryid: "",
          co_categoryid: "",
          oneCategoryid: "",
          twoCategoryid: "",
          coCategoryid: "",
          title: "",
          thumb: "",
          thumbUrl: "",
          postage: "",
          content: "",
          contentImg: "",
          stock: "",
          typeStock: 1,
          status: 1,
          is_save: 1,
      
          param: [],
          spec: [],
          option: []
        };
      }
    },
    /**新增/编辑 */
    finsh() {
      let formData = JSON.parse(JSON.stringify(this.form));
      formData.option = JSON.stringify(
        formData.option.filter(item => !item.disabled)
      );
      formData.spec = JSON.stringify(formData.spec);
      formData.param = JSON.stringify(formData.param);

      // formData.co_categoryid = this.co_categoryid;

      if (this.form.id) {
        edit_goods_info({
          goods_id: formData.goods_id,
          categoryid: formData.categoryid,
          co_categoryid: formData.co_categoryid,
          title: formData.title,
          thumb: formData.thumb,
          thumbUrl: formData.thumbUrl,
          postage: formData.postage,
          content: formData.content,
          contentImg: formData.contentImg,
          stock: formData.stock,
          typeStock: formData.typeStock,
          status: formData.status,
          is_save: formData.is_save,
          use_price: formData.use_price,
          param: formData.param,
          spec: formData.spec,
          option: formData.option
        }).then(res => {
          if (res.code == 200) {
            this.active = 0;
            this.$emit("freshTable");
            this.initProduct();
            this.$message.success(res.message);
          } else {
            this.$message.error(res.message);
          }
        });
      } else {
        add_goods_info(formData).then(res => {
          if (res.code == 200) {
            this.active = 0;
            this.$emit("freshTable");
            this.initProduct();
            this.$message.success(res.message);
          } else {
            this.$message.error(res.message);
          }
        });
      }
    },
    /**打开属性弹框 */
    openAttribute(index) {
      let val = "";
      this.parmarIndex = "";
      if (index) {
        this.parmarIndex = index;
        val = this.form.param[index];
      }
      this.$refs.attributeEdit.init(val);
    },
    /**保存属性 */
    saveAttribute(val) {
      if (this.parmarIndex) {
        this.form.param[this.parmarIndex] = val;
      } else {
        this.form.param.push(val);
      }
    },
    /**添加规格 */
    addSpecs() {
      // this.$set("form");

      this.form.spec.push({
        title: "",
        list: [{ name: "" }]
      });
    },
    /**生成规格表 */
    updateTable() {
      // console.log(this.form.spec);

      let option = [
        {
          title: "",
          name: "",
          thumb: "",
          goods_no: 0,
          price: 100,
          old_price: "0",
          purchase_price: "0",
          cost_price: "0",
          stock: "0",
          disabled: false
        }
      ]; //初始
      console.log(option);

      var items = this.form.spec;
      console.log(items);
      for (var i = 0; i < items.length; i++) {
        //循环得到每一个item对象
        //{"attributeName":"网络","attributeValue":["移动4G","联通4G","电信4G"]}
        option = this.addColumn(option, items[i].title, items[i].list);
      }
      // console.log(option)
      this.form.option = option;
    },
    /**删除图片 */
    handleRemove(index) {
      let thumbUrl = this.form.thumbUrl ? this.form.thumbUrl.split(",") : [];

      thumbUrl.splice(index, 1);
      this.form.thumbUrl = thumbUrl.join(",");
    },
    handleRemoveC() {
      let contentImg = this.form.contentImg
        ? this.form.contentImg.split(",")
        : [];

      contentImg.splice(index, 1);
      this.form.contentImg = contentImg.join(",");
    },
    /**上传回调 */
    specsSuccess(res, file, index) {
      console.log(index);
      if (res.code == 200) {
        this.$set(this.form.option[index], "thumb", res.data.file_url);
      } else {
        this.$message.error(res.message);

        return;
      }
    },
    /**主图上传回调 */

    handleSuccess(res, file) {
      if (res.code == 200) {
        this.form.thumb = res.data.file_url;
      } else {
        this.$message.error(res.message);
      }
    },
    handleAvatarSuccess(res, file) {
      if (res.code == 200) {
        let thumbUrl = this.form.thumbUrl ? this.form.thumbUrl.split(",") : [];
        thumbUrl.push(res.data.file_url);
        this.form.thumbUrl = thumbUrl.join(",");
      } else {
        this.$message.error(res.message);
      }
    },
    handleAvatarSucce(res, file) {
      if (res.code == 200) {
        let contentImg = this.form.contentImg
          ? this.form.contentImg.split(",")
          : [];
        contentImg.push(res.data.file_url);
        this.form.contentImg = contentImg.join(",");
      } else {
        this.$message.error(res.message);
      }
    },

    addColumn(list, columnName, columnValues) {
      var newList = []; //新的集合
      for (var i = 0; i < list.length; i++) {
        //list中的每一个对象,每一条SKU
        var oldRow = list[i];
        //给当前SKU添加规格
        for (var j = 0; j < columnValues.length; j++) {
          var newRow = JSON.parse(JSON.stringify(oldRow)); //深克隆
          newRow.name =
            (newRow.name ? newRow.name + "-" : "") + columnValues[j].name;
          newList.push(newRow);
        }
      }

      return newList;
    },

    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 4;

      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 4MB!");
      }
      return isLt2M;
    },
    changeEditor(e) {
      //console.log(e)
      this.form.content = e;
    },
    handleChange(value) {
      // console.log(value[value.length-1]);
      this.form.categoryid = value[value.length - 1];
    },
    handleChanges(value) {
      // console.log(value[value.length-1]);
      this.form.co_categoryid = value[value.length - 1];
    },

    onSubmit() {
      console.log("submit!");
    },
    next() {
      if (this.active++ > 2) this.active = 0;
    },

    back() {
      this.active--;
    }
  }
};
</script>
<style lang="less" >
.el-specItem {
  height: auto;
  -webkit-appearance: none;
  background-color: #fff;
  background-image: none;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  color: #606266;
  display: inline-block;
  font-size: inherit;
  height: 40px;
  line-height: 40px;
  outline: 0;

  -webkit-transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  width: 100%;
  .addBtn {
    margin-left: 10px;
  }
}
.specItem {
  border-bottom: 1px solid #d8d8d8;
  padding: 0 10px;
}
.specVal {
  display: flex;
  flex-wrap: wrap;
  .valTit {
    width: 60px;
  }
  .inputBox {
    position: relative;
    margin-right: 10px;
    i {
      position: absolute;
      right: 0;
      top: 0;
      cursor: pointer;
    }
  }
}
.flexP {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 40px;
    height: 40px;
    line-height: 40px;
    text-align: center;
  }
  .avatar {
    width: 40px;
    height: 40px;
    display: block;
  }
  .avatars {
    width: 40px;
    height: 40px;
    margin-right: 10px;
    position: relative;
    display: inline-block;
    .deleteIcon {
      position: absolute;
      right: -0;
      top: -0;
      line-height: 20px;
      color: #fff;
      cursor: pointer;
      background-color: rgba(0, 0, 0, 0.3);

      text-align: center;
      width: 20px;
      height: 20px;
    }
  }
}
.parmarBtn {
  position: relative;

  display: inline-block;
  margin-right: 8px;
  background: rgba(255, 255, 255, 1);
  border-radius: 2px;
  line-height: 1;
  border: 1px solid rgba(199, 199, 199, 1);
  padding: 7px 15px;
  box-sizing: border-box;
  i {
    position: absolute;
    right: -5px;
    top: -5px;
    color: #d81e06;
    cursor: pointer;
  }
}
.flexcenter {
  flex: 1;
  overflow-y: auto;
  .el-form-item {
    margin-bottom: 8px;
    margin-top: 8px;
  }
}
</style>